package com.xiaoshuidi.cloud.module.member.repository;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoshuidi.cloud.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.xiaoshuidi.cloud.framework.tenant.core.util.TenantUtils;
import com.xiaoshuidi.cloud.module.bpm.enums.task.BpmProcessInstanceResultEnum;
import com.xiaoshuidi.cloud.module.member.controller.admin.coupon.vo.BookingCouponSendVO;
import com.xiaoshuidi.cloud.module.member.controller.admin.coupon.vo.CouponListExeclVO;
import com.xiaoshuidi.cloud.module.member.controller.admin.coupon.vo.CouponQueryForm;
import com.xiaoshuidi.cloud.module.member.controller.admin.coupon.vo.NewSignCouponSendVO;
import com.xiaoshuidi.cloud.module.member.controller.admin.coupon.vo.OldBringNewCouponSendVO;
import com.xiaoshuidi.cloud.module.member.enums.coupon.CouponStatusEnum;
import com.xiaoshuidi.cloud.module.member.enums.coupon.CouponTypeEnum;
import com.xiaoshuidi.cloud.module.member.mapper.coupon.CouponMapper;
import com.xiaoshuidi.cloud.module.member.pojo.coupon.CouponEntity;
import com.xiaoshuidi.cloud.module.member.util.CustomDateUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


@Repository
@RequiredArgsConstructor
public class MemberCouponRepository extends ServiceImpl<CouponMapper, CouponEntity> {
    private final CouponMapper mapper;


    public Boolean updateStatusByBpmResult(Long tenantId, String businessKey, Integer result) {
        Date now = new Date();
        CouponEntity couponEntity = new CouponEntity();
        Long id = Long.parseLong(businessKey);
        couponEntity.setId(id);
        couponEntity.setReviewTime(now);
        TenantUtils.execute(tenantId, () -> {
            CouponEntity coupon = mapper.selectById(id);
            if (coupon == null) {
                return;
            }
            if (result.intValue() == BpmProcessInstanceResultEnum.APPROVE.getResult().intValue()) {
                if (coupon.getCouponType().intValue() == CouponTypeEnum.INTERNAL_EMPLOYEE_DISCOUNT.getNum().intValue()) {
                    couponEntity.setCouponStatus(CouponStatusEnum.IN_PROGRESS.getCode());
                } else {
                    boolean between = CustomDateUtil.isDateBetween(coupon.getActivityStartTime(), coupon.getActivityEndTime(), now);
                    if (between) {
                        couponEntity.setCouponStatus(CouponStatusEnum.IN_PROGRESS.getCode());
                    } else {
                        if (DateUtil.compare(coupon.getActivityStartTime(), now) > 0) {
                            //如果当前时间在活动开始时间之前那么是未开始
                            couponEntity.setCouponStatus(CouponStatusEnum.NOT_STARTED.getCode());
                        } else if (DateUtil.compare(now, coupon.getActivityEndTime()) > 0) {
                            //如果当前时间在活动结束时间之后
                            couponEntity.setCouponStatus(CouponStatusEnum.COMPLETED.getCode());
                        }
                    }
                }

            } else if (result.intValue() == BpmProcessInstanceResultEnum.PROCESS.getResult().intValue()) {
                couponEntity.setCouponStatus(CouponStatusEnum.BEING_APPROVED.getCode());
            } else if (result.intValue() == BpmProcessInstanceResultEnum.REJECT.getResult().intValue()) {
                couponEntity.setCouponStatus(CouponStatusEnum.APPROVAL_REJECTION.getCode());
            } else if (result.intValue() == BpmProcessInstanceResultEnum.CANCEL.getResult().intValue()) {
                couponEntity.setCouponStatus(CouponStatusEnum.APPROVAL_CANCEL.getCode());
            } else if (result.intValue() == BpmProcessInstanceResultEnum.BACK.getResult().intValue()) {
                couponEntity.setCouponStatus(CouponStatusEnum.APPROVAL_REJECTION.getCode());
            }
            mapper.updateById(couponEntity);
        });
        return true;
    }

    /**
     * 判断是否给用户发放预定优惠券
     *
     * @param bookingCouponSendVO
     * @return
     */
    public CouponEntity validBookingSendCoupon(BookingCouponSendVO bookingCouponSendVO) {
        //前提时审核状态为进行中状态
        //1在活动期限内2符合活动门店的个人租客3 这里加了在预定开始日期和结束日期以及预定金额大于等于规定的预定金
//        LocalDateTime now = LocalDateTime.now();
//        LambdaQueryWrapperX<CouponEntity> wrapperX = new LambdaQueryWrapperX<CouponEntity>()
//                .eq(CouponEntity::getCouponStatus, CouponStatusEnum.IN_PROGRESS.getCode())
//                .eq(CouponEntity::getCouponType, CouponTypeEnum.RESERVATION_DISCOUNT.getNum())
//                .leIfPresent(CouponEntity::getActivityStartTime, now)
//                .geIfPresent(CouponEntity::getActivityEndTime, now)
//                .eqIfPresent(CouponEntity::getTenantId, bookingCouponSendVO.getTenantId())
//                .eqIfPresent(CouponEntity::getActivityStore, bookingCouponSendVO.getApartmentId())
//                .leIfPresent(CouponEntity::getScheduledStartTime, bookingCouponSendVO.getBookingDate())
//                .geIfPresent(CouponEntity::getScheduledEndTime, bookingCouponSendVO.getBookingDate())
//                .leIfPresent(CouponEntity::getScheduledAmount, bookingCouponSendVO.getDeposit());
//        List<CouponEntity> list = mapper.selectList(wrapperX);

        List<CouponEntity> list = mapper.validBookingSendCoupon(bookingCouponSendVO);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;


    }

    /**
     * 判断是否能发放老带新优惠券
     *
     * @param oldBringNewCouponSendVO
     * @return
     */
    public CouponEntity validOldBringsNewSendCoupon(OldBringNewCouponSendVO oldBringNewCouponSendVO) {
        //前提时审核状态为进行中状态
        //1在活动期限内2符合活动门店的新客3签约日期在签约起止日期内，合同起止日期完全在租赁起止月份内
//        LocalDateTime now = LocalDateTime.now();
//        Long month = DateUtil.betweenMonth(oldBringNewCouponSendVO.getStartTime(), oldBringNewCouponSendVO.getEndTime(), true);
//        LambdaQueryWrapperX<CouponEntity> wrapperX = new LambdaQueryWrapperX<CouponEntity>()
//                .eq(CouponEntity::getCouponStatus, CouponStatusEnum.IN_PROGRESS.getCode())
//                .eq(CouponEntity::getCouponType, CouponTypeEnum.OLD_WITH_NEW_DISCOUNT.getNum())
//                .leIfPresent(CouponEntity::getActivityStartTime, now)
//                .geIfPresent(CouponEntity::getActivityEndTime, now)
//                .eqIfPresent(CouponEntity::getActivityStore, oldBringNewCouponSendVO.getNewApartmentId())
//                .eqIfPresent(CouponEntity::getTenantId, oldBringNewCouponSendVO.getTenantId())
//                .leIfPresent(CouponEntity::getSigningStartTime, oldBringNewCouponSendVO.getOldBringsNewDate())
//                .geIfPresent(CouponEntity::getSigningEndTime, oldBringNewCouponSendVO.getOldBringsNewDate())
//                .leIfPresent(CouponEntity::getMiniLeaseMonth, month.intValue())
//                .geIfPresent(CouponEntity::getMaxLeaseMonth, month.intValue());
//        ;
//        List<CouponEntity> list = mapper.selectList(wrapperX);
        Long month = DateUtil.betweenMonth(oldBringNewCouponSendVO.getStartTime(), oldBringNewCouponSendVO.getEndTime(), true);
        List<CouponEntity> list = mapper.validOldBringsNewSendCoupon(month, oldBringNewCouponSendVO);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    public CouponEntity validNewSignSendCoupon(NewSignCouponSendVO newSignCouponSendVO) {
        //前提时审核状态为进行中状态
        //1在活动期限内2符合活动门店的新客3.签约日期在签约起止日期内，合同起止日期完全在租赁起止月份内
        Long month = DateUtil.betweenMonth(newSignCouponSendVO.getStartTime(), newSignCouponSendVO.getEndTime(), true);
//        LocalDateTime now = LocalDateTime.now();
//        LambdaQueryWrapperX<CouponEntity> wrapperX = new LambdaQueryWrapperX<CouponEntity>()
//                .eq(CouponEntity::getCouponStatus, CouponStatusEnum.IN_PROGRESS.getCode())
//                .eq(CouponEntity::getCouponType, CouponTypeEnum.NEW_SIGNING_DISCOUNT.getNum())
//                .leIfPresent(CouponEntity::getActivityStartTime, now)
//                .geIfPresent(CouponEntity::getActivityEndTime, now)
//                .eqIfPresent(CouponEntity::getActivityStore, newSignCouponSendVO.getApartmentId())
//                .leIfPresent(CouponEntity::getSigningStartTime, newSignCouponSendVO.getNewSignDate())
//                .geIfPresent(CouponEntity::getSigningEndTime, newSignCouponSendVO.getNewSignDate())
//                .eqIfPresent(CouponEntity::getTenantId, newSignCouponSendVO.getTenantId())
//                .leIfPresent(CouponEntity::getMiniLeaseMonth, month.intValue())
//                .geIfPresent(CouponEntity::getMaxLeaseMonth, month.intValue());
//        List<CouponEntity> list = mapper.selectList(wrapperX);

        List<CouponEntity> list = mapper.validNewSignSendCoupon(month, newSignCouponSendVO);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    public void deduceStock(Long couponId, Long couponNum) {
        mapper.deduceStock(couponId, couponNum);
    }

    public void addStock(Long couponId, Long couponNum) {
        mapper.addStock(couponId, couponNum);
    }

    /**
     * 查询优惠券活动中状态为未开始状态和正在进行中状态
     *
     * @return
     */
    public List<CouponEntity> getNotStartAndInProgressList() {
        LambdaQueryWrapperX<CouponEntity> wrapperX = new LambdaQueryWrapperX<CouponEntity>()
                .in(CouponEntity::getCouponStatus, Arrays.asList(CouponStatusEnum.NOT_STARTED.getCode().intValue(),
                        CouponStatusEnum.IN_PROGRESS.getCode().intValue()));
        return mapper.selectList(wrapperX);
    }

    public void batchUpdateCoupon(List<CouponEntity> list) {
        this.updateBatchById(list);
    }

    public List<CouponListExeclVO> exportCouponList(CouponQueryForm form) {
        return mapper.exportCouponList(form);
    }

    public CouponEntity selectByCouponName(String couponName) {
        LambdaQueryWrapperX<CouponEntity> wrapperX = new LambdaQueryWrapperX<CouponEntity>()
                .eqIfPresent(CouponEntity::getCouponName, couponName);
        List<CouponEntity> list = mapper.selectList(wrapperX);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    public void addSendStock(Long couponId, Long couponNum) {
        mapper.addSendStock(couponId, couponNum);
    }

    public void deduceSendStock(Long id, Long couponNum) {
        mapper.deduceSendStock(id, couponNum);
    }
}
